package cn.com.se.设计模式.代理模式.JDK动态代理;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * 代理类
 */
public class HelloProxy implements InvocationHandler {

    private Object object;

    public HelloProxy(Object object){
        this.object = object;
    }

    public void before(){
        System.out.println("before");
    }

    public void after(){
        System.out.println("after");
    }

    /**
     * 反射调用委托类方法
     * @param proxy
     * @param method
     * @param args
     * @return
     * @throws Throwable
     */
    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        before();
        Object result = method.invoke(object,args);
        after();
        return null;
    }

    /**
     * 获取代理对象
     * @param <T>
     * @return
     */
    public  <T>T getProxyObj(){
        return (T)Proxy.newProxyInstance(object.getClass().getClassLoader(),object.getClass().getInterfaces(),this);
    }
}
